package com.aliengen.thingple.driverapp.service;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;

import com.aliengen.thingple.driverapp.R;
import com.aliengen.thingple.driverapp.device.CMCHandler;
import com.aliengen.thingple.driverapp.device.ThingpleDevice;
import com.aliengen.thingple.driverapp.ui.activities.LoadingActivity;

/**
 * This class is part of the Thingple mobile application for the CMC168 Handheld reader.
 *
 * Copyright AlienGen Limited 2016. All rights reserved.
 *
 * @author Timothé Mermet-Buffet <tim@aliengen.com>
 */
public class ThingpleService  extends Service {
    public ThingpleDevice device;

    private final IBinder binder = new ThingpleBinder();

    @Override
    public IBinder onBind(Intent intent) {
        System.out.println("Service is Binded!");
        return binder;
    }

    @Override
    public boolean onUnbind(Intent intent){
        System.out.println("Service is Unbinded!");
        return true;
    }

    public void SetBinder(Context context, CMCHandler handler){
        device = new ThingpleDevice(context, handler);
    }

    public class ThingpleBinder extends Binder {
        ThingpleService GetService() {
            return ThingpleService.this;
        }
    }

    @Override
    public void onCreate(){
        super.onCreate();
        Intent notificationIntent = new Intent(this, LoadingActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(
                this);
        Notification notification = builder.setContentIntent(pendingIntent)
                .setSmallIcon(R.drawable.ic_launcher).setTicker("CMCID Service").setWhen(System.currentTimeMillis())
                .setAutoCancel(true).setContentTitle("CMCID")
                .setContentText("CMCID Service").build();

        startForeground(1, notification);
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        device = null;
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId){
        flags = START_STICKY;
        return super.onStartCommand(intent, flags, startId);
    }
}
